import axios from 'axios';
import store from '../store';

const service = axios.create({
  baseURL: '/api', // 代理到 ruoyi 后端
  timeout: 5000
});
let downloadLoadingInstance;

service.interceptors.request.use(config => {
  const token = store.state.token;
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token;
  }
  return config;
});

service.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response && error.response.status === 401) {
      // token 失效，跳转登录
      store.dispatch('logout');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 通用下载方法
export function download(url, params, filename, config) {
    downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
    });
    return service
        .post(url, params, {
            transformRequest: [
                (params) => {
                    return tansParams(params);
                },
            ],
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            responseType: "blob",
            ...config,
        })
        .then(async (data) => {
            const isBlob = blobValidate(data);
            if (isBlob) {
                const blob = new Blob([data]);
                saveAs(blob, filename);
            } else {
                const resText = await data.text();
                const rspObj = JSON.parse(resText);
                const errMsg =
                    errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
                Message.error(errMsg);
            }
            downloadLoadingInstance.close();
        })
        .catch((r) => {
            console.error(r);
            Message.error("下载文件出现错误，请联系管理员！");
            downloadLoadingInstance.close();
        });
}

export default service;
